package io.hei.modules.sys.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 测试类，没有使用
 */
@RestController
@RequestMapping("/sys/down")
public class DownController extends HttpServlet {

    @RequestMapping(value = "/download/{origin_name}/{file_id}")
    public void doGet(HttpServletRequest request, HttpServletResponse response,
                      @PathVariable("origin_name") String origin_name,
                      @PathVariable("file_id") String file_id)
            throws ServletException, IOException {
        String fileName = origin_name;
        // 设置响应头参数值
        System.out.println("H:\\upload\\" + origin_name);
        String contentType = this.getServletContext().getMimeType("H:\\upload\\" + origin_name);
        String contentDisposition = "attachment;fileName="
                + fileNameEncoding(fileName, request);
        response.setHeader("Content-Type", contentType);
        response.setHeader("Content-Disposition", contentDisposition);

        // 设置响应头
        ServletOutputStream output = response.getOutputStream();
        FileInputStream input = new FileInputStream("H:\\upload\\" + origin_name);
        // 将输入流中的文件写入到输出流
        IOUtils.copy(input, output);
        input.close();
    }

    public String fileNameEncoding(String fileName, HttpServletRequest request)
            throws IOException {
        String agent = request.getHeader("User-Agent");
        if (agent.contains("Firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            fileName = "=?utf-8?B?"
                    + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
        } else {
            fileName = URLEncoder.encode(fileName, "utf-8");
        }
        return fileName;
    }
}
